package com.my.jli.webapi;

import com.my.jli.Service.MyFileService;
import com.my.jli.Service.TeacherService;
import com.my.jli.entity.MyFile;
import com.my.jli.entity.Teacher;
import com.my.jli.util.FileUtil;
import com.my.jli.util.SignCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @ClassName TeacherRestController
 * @Description
 * @Author MaYu
 * @Date 2022/1/27 19:29
 * @Version 1.0
 **/
@RestController
@RequestMapping("/webapi/teacher")
public class TeacherRestController {

    @Value("${file-save-path}")
    private String fileSavePath;

    private TeacherService teacherService;
    //set方法注入service
    @Autowired
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    private MyFileService myFileService;
    @Autowired
    public void setMyFileService(MyFileService myFileService) {
        this.myFileService = myFileService;
    }

    //获取所有教师
    @GetMapping("/list")
    public List<Teacher> getAll(){
        return teacherService.getAll();
    }

    @GetMapping("/login")
    //教师后台登录
    public int login(HttpSession session, String num, String pwd,
                     @RequestParam(value = "remember",defaultValue = "0") Integer remember){
        //根据工号密码查找教师
        List<Teacher> teachers = teacherService.findByNumAndPwd(num, pwd);
        //如果匹配到一个教师
        if (teachers.size() == 1){
            //写入session
            session.setAttribute("teacher", teachers.get(0));
            //成功，返回1
            return 1;
        } else {
            //失败，返回-1
            return -1;
        }
    }

    /**
     * 获取签到码
     * @param session session
     * @param currentDateTime 当前时间
     * @return signCodeUtil
     */
    @RequestMapping("/getSignCode")
    public SignCodeUtil getCode(HttpSession session, Long currentDateTime){
        //先查看session中有没有验证码工具对象
        SignCodeUtil signCodeUtil = (SignCodeUtil) session.getAttribute("signCodeUtil");

        //如果没有，则新创建一个
        if (signCodeUtil == null){
            signCodeUtil = new SignCodeUtil();
            session.setAttribute("signCodeUtil", signCodeUtil);
            return signCodeUtil;
        } else {//如果有
            //判断上一个验证码是否还有效
            if (currentDateTime < signCodeUtil.getEndDate()){
                //有效，则返回以前的验证码工具对象
                return signCodeUtil;
            } else {
                //无效，则重新生成验证码
                SignCodeUtil signCodeUtil1 = new SignCodeUtil();
                session.setAttribute("signCodeUtil", signCodeUtil1);
                return signCodeUtil1;
            }
        }
    }

    /**
     * 获取已经签到的人数
     * @return 已签到的人数
     */
    @RequestMapping("/getSignCount")
    public int getSignCount(HttpSession session){
        //先查看session中有没有验证码工具对象
        SignCodeUtil signCodeUtil = (SignCodeUtil) session.getAttribute("signCodeUtil");
        if (signCodeUtil == null){
            return -1;
        } else {
            return signCodeUtil.getSignStu().size();
        }
    }

    @RequestMapping("/setSignCodeUtil")
    public void setSignCodeUtil(HttpSession session, Integer remainingTime){
        SignCodeUtil signCodeUtil = (SignCodeUtil) session.getAttribute("signCodeUtil");
        signCodeUtil.setEndDate(signCodeUtil.getStartDate() + remainingTime);
        session.setAttribute("signCodeUtil", signCodeUtil);
    }

    /**
     * 学习文件上传
     * @param file 传入的文件对象
     * @return 状态码，1=成功，-1=失败
     */
    @RequestMapping("/upload")
    public int uploadFile(MultipartFile file, @RequestParam(value = "isTeacher", defaultValue = "false") boolean isTeacher){
        if (file != null && file.getSize() > 0){
            //重命名文件
            String filename = file.getOriginalFilename();
            String fileNameNew = FileUtil.getFileNameNew(filename);
            //生成动态文件夹
            String datePath = FileUtil.getDatePath();
            String filePath = fileSavePath + "/" + datePath;
            File file1 = new File(filePath);
            if (!file1.exists()){
                //如果路径不存在则新建
                boolean b = file1.mkdirs();
                if (!b){
                    //如果文件路径创建失败返回-1
                    return -1;
                }
            }
            File file2 = new File(filePath + "/" + fileNameNew);
            System.out.println(file2.getPath());
            try {
                file.transferTo(file2);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //设置文件信息
            MyFile myFile = new MyFile();
            myFile.setFilename(filename);
            //设置路径
            myFile.setFilepath(datePath + "/" + fileNameNew);
            myFile.setSize(file.getSize());
            myFile.setUpdateDate(new Date());
            assert filename != null;
            myFile.setType(filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(Locale.ROOT));
            if (isTeacher){
                //如果是老师上传，直接过审
                myFile.setJurisdiction(1);
            } else {
                //不是老师上传设置未过审
                myFile.setJurisdiction(0);
            }

            //存入数据库
            myFileService.addMyFile(myFile);
            return 1;
        } else {
            return -1;
        }
    }
}
